package com.example.online_gobang.api;

import com.example.online_gobang.mapper.UserMapper;
import com.example.online_gobang.model.User;
import com.example.online_gobang.tools.Constant;
import com.example.online_gobang.tools.ResponseBodyMessage;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 74646
 * Date: 2022-11-14
 * Time: 15:11
 */
@RestController
public class UserAPI {

    @Resource
    private UserMapper userMapper;

    // 使用 BCrypt 对密码进行加密
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/login")
    @ResponseBody
    public ResponseBodyMessage<User> login(@RequestParam String username,@RequestParam String password,HttpServletRequest request){
        /**
         *  根据 username 到数据库中进行查询
         *  如果能找到匹配的用户，并且密码也一致，就认为登录成功
         */
        User user = userMapper.selectByName(username);
        System.out.println("登录的用户："+ username);
        if(user != null){
            System.out.println("登录成功");

            // 判断当前用户输入的密码(password) 与 数据库中查询到的密码(加密的密码，getPassword())是否匹配
            boolean flag = bCryptPasswordEncoder.matches(password,user.getPassword());

            if(!flag){
                // 密码不匹配，登录失败
                return new ResponseBodyMessage<>(-200,"用户名或密码错误",user);
            }
            // 如果登录成功就将信息写入到 session 中（在 session 中存储了一个用户信息对象,此后可以随时从 session 中将这个对象取出来进行一些操作）
            request.getSession().setAttribute(Constant.USER_SESSION_KEY,user);
            // 状态码为200,表示登录成功,并返回用户信息
            return   new ResponseBodyMessage<>(200,"登录成功",user);
        }else {
            // 登录失败,返回一个空的对象
            System.out.println("登录失败");
            return new ResponseBodyMessage<>(-200,"用户名或密码错误",user);
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    public ResponseBodyMessage<Boolean> register(@RequestParam String username, @RequestParam String password){
        User user1 = userMapper.selectByName(username);
        if(user1 != null) {
            return new ResponseBodyMessage<>(-200,"当前用户已经存在",false);
        }else {
            User user = new User();
            String newPassword = bCryptPasswordEncoder.encode(password);
            user.setUsername(username);
            user.setPassword(newPassword);
            boolean flag = userMapper.insert(user);
            if(flag == true){
                return new ResponseBodyMessage<>(200,"注册成功",true);
            }else{
                return new ResponseBodyMessage<>(-200,"注册失败",false);
            }
        }
    }

    @RequestMapping("/userInfo")
    @ResponseBody
    public ResponseBodyMessage<User> getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(Constant.USER_SESSION_KEY); // 从会话中获取 User 对象
        User newUser = userMapper.selectByName(user.getUsername());
        if(user != null){
            return new ResponseBodyMessage<>(200,"获取成功",newUser);
        }else {
            System.out.println("没有该用户");
            return new ResponseBodyMessage<>(-200,"获取失败",user);
        }
    }

    @RequestMapping("/logout")
    public void userLogout(HttpServletRequest request, HttpServletResponse response) throws IOException, IOException {
        HttpSession session = request.getSession(false);
        // 拦截器的拦截, 所以不可能出现session为空的情况
        session.removeAttribute(Constant.USER_SESSION_KEY);
        response.sendRedirect("login.html");
    }
}
